import "./CustomRichText.scss";
import E from "wangeditor";
import React, { Component } from "react";
import { adminToken } from "@/utils/variable";
import CustomModal from "@/components/common/CustomModal";
import PropTypes from "prop-types";
const { BtnMenu } = E;
let clickH5Icon = null;
let editor = null;
let canUpdate = true;
class CustomRichText extends Component {
    constructor() {
        super();
        this.state = {
            richTextVisible: false,
            h5Text: "",
            updateCount: 0,
        };
    }
    UNSAFE_componentWillReceiveProps(props) {
        if (canUpdate) {
            if (props.htmlString) {
                canUpdate = false;
                editor.txt.html(props.htmlString);
            }
        }
    }
    componentWillUnmount() {
        canUpdate = true;
    }
    componentDidMount() {
        this.initEditor();
    }
    initEditor = () => {
        editor = new E("#rightTextDom");
        let H5MenuKey = "h5Menu";
        editor.config.menus = [
            "head",
            "bold",
            "fontSize",
            "fontName",
            "italic",
            "underline",
            "strikeThrough",
            "indent",
            "lineHeight",
            "foreColor",
            "backColor",
            "link",
            "list",
            "justify",
            "quote",
            "emoticon",
            "table",
            "code",
            "splitLine",
            "undo",
            "redo",
            "image",
        ];
        editor.menus.extend(H5MenuKey, H5Menu);
        editor.config.menus = editor.config.menus.concat(H5MenuKey);
        editor.config.uploadImgServer = process.env.REACT_APP_FILE;
        editor.config.uploadImgHeaders = {
            Authorization: `Bearer ${localStorage[adminToken]}`,
        };
        editor.config.uploadFileName = "file";
        editor.config.showFullScreen = true;
        editor.config.uploadImgHooks = {
            customInsert(insertImgFn, result) {
                insertImgFn(`${process.env.REACT_APP_FILE}/${result.originalname}`);
            },
        };
        // 配置 onchange 回调函数
        editor.config.onchange = newHtml => {
            this.props.onChange(newHtml);
        };
        editor.create();
        clickH5Icon = () => {
            this.setState({
                richTextVisible: true,
                h5Text: editor.txt.html(),
            });
        };
    };
    render() {
        const { richTextVisible, h5Text } = this.state;
        return (
            <>
                <div className="width-100" id="rightTextDom"></div>
                <CustomModal
                    onOk={() => {
                        editor.txt.html(this.state.h5Text);
                        this.setState({ richTextVisible: false });
                    }}
                    onCancel={() => this.setState({ richTextVisible: false })}
                    visible={richTextVisible}
                    okText="确定"
                >
                    {richTextVisible ? (
                        <textarea defaultValue={h5Text} onChange={e => this.setState({ h5Text: e.target.value })} className="H5TextArea" rows="20" />
                    ) : (
                        ""
                    )}
                </CustomModal>
            </>
        );
    }
}
CustomRichText.propTypes = {
    htmlString: PropTypes.string,
};
CustomRichText.defaultProps = {
    htmlString: "",
};
export default CustomRichText;

// 第一，菜单 class ，Button 菜单继承 BtnMenu class
class H5Menu extends BtnMenu {
    constructor(editor) {
        const $elem = E.$(`<div class="h5-icon"></div>`);
        super($elem, editor);
    }
    // 菜单点击事件
    clickHandler() {
        // 做任何你想做的事情
        // 可参考【常用 API】文档，来操作编辑器
        clickH5Icon();
    }
    // 菜单是否被激活（如果不需要，这个函数可以空着）
    // 1. 激活是什么？光标放在一段加粗、下划线的文本时，菜单栏里的 B 和 U 被激活，如下图
    // 2. 什么时候执行这个函数？每次编辑器区域的选区变化（如鼠标操作、键盘操作等），都会触发各个菜单的 tryChangeActive 函数，重新计算菜单的激活状态
    tryChangeActive() {
        // 激活菜单
        // 1. 菜单 DOM 节点会增加一个 .w-e-active 的 css class
        // 2. this.this.isActive === true
        this.active();

        // // 取消激活菜单
        // // 1. 菜单 DOM 节点会删掉 .w-e-active
        // // 2. this.this.isActive === false
        // this.unActive()
    }
}
